package com.base.controller.coupon_api;

import com.alibaba.fastjson.JSONObject;
import com.base.po.coupon_new.CouponGoodsNew;
import com.base.po.coupon_sdk.CouponInfoUtilNew;
import com.base.po.param.NetState;
import com.base.po.voip_coupon.CouponBrand;
import com.base.po.voip_coupon.CouponCategory;
import com.base.po.voip_coupon.return_po.BrandPo;
import com.base.po.voip_coupon.return_po.BrandsPo;
import com.base.po.voip_coupon.return_po.CategoryPo;
import com.base.po.voip_coupon.return_po.GoodsPro;
import com.base.service.COUPON.*;
import com.base.service.SubscribersService;
import com.base.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 365优惠券
 *
 * @author K
 */
@Slf4j
@RestController
@RequestMapping("/coupon")
public class CouponController {
    private final UsersService usersService;
    private final SubscribersService subscribersService;
    private final CouponCategoryService couponCategoryService;
    private final CouponBrandService couponBrandService;
    private final CouponGoodsNewService couponGoodsNewService;
    private final CouponOrderService couponOrderService;
    private final CouponPayOrderService couponPayOrderService;

    @Autowired
    public CouponController(UsersService usersService, SubscribersService subscribersService, CouponCategoryService couponCategoryService, CouponBrandService couponBrandService, CouponGoodsNewService couponGoodsNewService, CouponOrderService couponOrderService, CouponPayOrderService couponPayOrderService) {
        this.usersService = usersService;
        this.subscribersService = subscribersService;
        this.couponCategoryService = couponCategoryService;
        this.couponBrandService = couponBrandService;
        this.couponGoodsNewService = couponGoodsNewService;
        this.couponOrderService = couponOrderService;
        this.couponPayOrderService = couponPayOrderService;
    }

    // 365优惠券首页
    @RequestMapping(value = "/index", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState index(HttpServletRequest request, String parentId, String userId) throws Exception {
        NetState netState = new NetState();

//        if (parentId == null || parentId.isEmpty()) {
//            netState.setErrorCode(NetState.PARAMS_ERROR);
//            netState.setData("数据异常");
//            return netState;
//        }
        parentId=null;
        // 查询所有分类
        List<CouponCategory> categories = couponCategoryService.selectAll(null, parentId, 2);

        // 返回所有分类
        List<CategoryPo> categoryPos = new ArrayList<>();
        // 返回所有品牌
        List<BrandPo> brandPos = null;
        List<BrandsPo> brandsPos = new ArrayList<>();
        // 返回推荐品牌
        List<BrandPo> recommendBrandPos = new ArrayList<>();
        for (CouponCategory category : categories){
            // 分类
            CategoryPo categoryPo = new CategoryPo();
            categoryPo.setId(category.getId());
            categoryPo.setCategoryName(category.getCategory());
            categoryPos.add(categoryPo);

            // 品牌
            brandPos = new ArrayList<>();
            BrandsPo brandsPo = new BrandsPo();
            brandsPo.setCategoryId(category.getId());
            brandsPo.setCategoryName(category.getCategory());
            List<CouponBrand> brands = couponBrandService.selectAll(null, parentId, category.getId(), null, 2);
            for (CouponBrand brand : brands){
                BrandPo brandPo = new BrandPo();
                brandPo.setId(brand.getId());
                brandPo.setBrandName(brand.getCategory());
                brandPo.setBrandPic(brand.getPic());
                brandPos.add(brandPo);
                if (brand.getLevel() != null && brand.getLevel() == 1){
                    recommendBrandPos.add(brandPo);
                }
            }
            brandsPo.setBrandPos(brandPos.isEmpty() ? null : brandPos);
            brandsPos.add(brandsPo);
        }

        Map<String, Object> map = new HashedMap();
        map.put("categories", categoryPos);
        map.put("brands", brandsPos);
        map.put("recommendBrands", recommendBrandPos);

        netState.setErrorCode(NetState.SUCCESS_CONN);
        netState.setData("查询成功");
        netState.setJson(map);
        return netState;
    }

    // 365优惠券商品
    @RequestMapping(value = "/goods", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState goods(HttpServletRequest request, String parentId, String userId, String categoryId, String brandId) throws UnsupportedEncodingException {
        NetState netState = new NetState();

//        if (parentId == null || parentId.isEmpty() || brandId == null || brandId.isEmpty()) {
//            netState.setErrorCode(NetState.PARAMS_ERROR);
//            netState.setData("数据异常");
//            return netState;
//        }

        parentId=null;
        // 查询品牌
        List<CouponBrand> brands = couponBrandService.selectAll(null, parentId, categoryId, null, 2);
        // 返回品牌
        List<BrandPo> brandPos = new ArrayList<>();
        for (CouponBrand brand : brands){
            BrandPo brandPo = new BrandPo();
            brandPo.setId(brand.getId());
            brandPo.setBrandName(brand.getCategory());
            brandPo.setBrandPic(brand.getPic());
            brandPos.add(brandPo);
        }

        // 查询商品
        List<CouponGoodsNew> goodses = couponGoodsNewService.selectAllDetail(null, parentId, brandId);
        // 返回商品
        List<GoodsPro> goodsPos = new ArrayList<>();

        for (CouponGoodsNew goods : goodses){
            GoodsPro goodsPro=new GoodsPro();
            goodsPro.setCouponGoodsNew(goods);
            try{
                String stockresult= CouponInfoUtilNew.getStock(goods.getGoodsNo());
                JSONObject jsonObject=JSONObject.parseObject(stockresult);
                goodsPro.setStock(jsonObject.getString("stock_num"));
            }catch (Exception e){
                log.warn("[接口异常]");
                goodsPro.setStock("0");
            }
            goodsPos.add(goodsPro);
        }

        Map<String, Object> map = new HashedMap();
        map.put("brands", brandPos.isEmpty() ? null : brandPos);
        map.put("goodses", goodsPos.isEmpty() ? null : goodsPos);

        netState.setErrorCode(NetState.SUCCESS_CONN);
        netState.setData("查询成功");
        netState.setJson(map);
        return netState;
    }

    // 365优惠券商品
//    @RequestMapping(value = "/payUrl", method = {RequestMethod.POST, RequestMethod.GET})
//    public  NetState  getPayUrl(String goodsno){
//
//
//        return new NetState("",NetState.SUCCESS_CONN,null);
//    }


//    // 365优惠券订单
//    @RequestMapping(value = "/orders", method = {RequestMethod.POST, RequestMethod.GET})
//    public @ResponseBody
//    NetState orders(HttpServletRequest request, String parentId, String userId, Integer orderStatus, Integer status, Integer pageNo){
//        NetState netState = new NetState();
//
//        if (parentId == null || parentId.isEmpty() || userId == null || userId.isEmpty()) {
//            netState.setErrorCode(NetState.PARAMS_ERROR);
//            netState.setData("数据异常");
//            return netState;
//        }
//
//        if (status == 0){
//            status = null;
//        }
//
//        // 查询订单
//        Page page = new Page();
//        page.setCurrentPageNo(pageNo);
//        page.setRecordTotal(couponOrderService.countAll(parentId, userId, orderStatus, status));
//        List<CouponOrder> orders = couponOrderService.selectAll(page, parentId, userId, orderStatus, status);
//        // 返回订单
//        List<OrdersPo> ordersPos = new ArrayList<>();
//        for (CouponOrder order : orders){
//            CouponPayOrder payOrder = couponPayOrderService.selectByPrimaryKey(order.getId());
//
//            OrdersPo ordersPo = new OrdersPo();
//            ordersPo.setId(order.getId());
//            ordersPo.setProductId(order.getProductid());
//            ordersPo.setProductName(payOrder.getProductname());
//            ordersPo.setUnitPrice(payOrder.getUnitprice());
//            ordersPo.setCreateTime(order.getCouponcreatetime());
//            ordersPo.setCreateTime(order.getCouponcreatetime());
//            ordersPo.setEndTime(Produce.plusDay(1, order.getCouponcreatetime()));
//            ordersPo.setStatus(order.getStatus());
//            ordersPos.add(ordersPo);
//        }
//
//        netState.setErrorCode(NetState.SUCCESS_CONN);
//        netState.setData("查询成功");
//        netState.setJson(pageNo > page.getPageTotal() ? null : ordersPos.size() > 0 ? ordersPos : null);
//        return netState;
//    }
//
//    // 365优惠券订单详情
//    @RequestMapping(value = "/orderDetails", method = {RequestMethod.POST, RequestMethod.GET})
//    public @ResponseBody
//    NetState orderDetails(HttpServletRequest request, String orderId){
//        NetState netState = new NetState();
//
//        if (orderId == null || orderId.isEmpty()) {
//            netState.setErrorCode(NetState.PARAMS_ERROR);
//            netState.setData("数据异常");
//            return netState;
//        }
//
//        // 订单信息
//        CouponOrder order = couponOrderService.selectByPrimaryKey(orderId);
//        // 订单信息
//        CouponPayOrder payOrder = couponPayOrderService.selectByPrimaryKey(orderId);
//        // 商品信息
////        CouponGoods goods = couponGoodsService.selectByPrimaryKey(order.getProductid());
//
//        OrderPo orderPo = new OrderPo();
//        orderPo.setProductId(payOrder.getProductid());
//        orderPo.setProductName(payOrder.getProductname());
//        orderPo.setCardType(order.getCardtype());
//        orderPo.setCardNo(order.getCardno());
//        orderPo.setCardPwd(order.getCardpwd());
//        orderPo.setLinkUrl(order.getLinkurl());
//        orderPo.setUniqueCode(order.getUniquecode());
//        orderPo.setUnitPrice(payOrder.getUnitprice());
//        orderPo.setCreateTime(order.getCouponcreatetime());
//        orderPo.setEndTime(Produce.plusDay(1, order.getCouponcreatetime()));
////        orderPo.setSaveContent(goods.getShowcontent());
//        orderPo.setStatus(order.getStatus());
//        orderPo.setFlag(order.getFlag());
//
//        netState.setErrorCode(NetState.SUCCESS_CONN);
//        netState.setData("查询成功");
//        netState.setJson(orderPo);
//        return netState;
//    }
//
//    // 365优惠券订单退款申请
//    @RequestMapping(value = "/orderRefund", method = {RequestMethod.POST, RequestMethod.GET})
//    public @ResponseBody
//    NetState orderRefund(HttpServletRequest request, Integer orderFlag, Integer refundStatus){
//        NetState netState = new NetState();
//
//        if (orderFlag == null) {
//            netState.setErrorCode(NetState.PARAMS_ERROR);
//            netState.setData("数据异常");
//            return netState;
//        }
//
//        // 优惠券订单信息
//        CouponOrder order = couponOrderService.selectByFlag(orderFlag);
//        switch (refundStatus){
//            case 0:
//                order.setStatus(2);
//                break;
//            case 1:
//                order.setStatus(1);
//                break;
//        }
//        int code = couponOrderService.updateByPrimaryKeySelective(order);
//        if (code == 1){
//            netState.setErrorCode(NetState.SUCCESS_CONN);
//            netState.setData("退款申请成功");
//        }else {
//            netState.setErrorCode(NetState.ERROR_OPERATE);
//            netState.setData("退款申请失败");
//        }
//
//        return netState;
//    }
}
